var __docTpl__;

$(function() {
	initBlockUI();
	initApplyGo();
	initCancelButton();
	initAccessoryAddition();
	initShowDocReceiver();
	initDocReceiverSelection();
	initDocReceiverOK();
	initPage();
});

// 取消按钮
function initCancelButton() { $("#cancel_apply").click(function() {	if (window.confirm("确定取消本次申请？"))	window.close(); return false; }); }
// 初始化附件添加
function initAccessoryAddition()
{
	$("#add_accessory_button").click(function() {
		window.open("new_app_accessory.php", "上传附件", "toolbar=no,menubar=no,width=400,height=400");
	});
}
// 附件处理
function addAccessory(ac)
{
	$("#accessory_list").val(ac);
	var accessories = ac.split(";;");
	$("#accessory_list_select").html("");
	$.each(accessories, function(i, n) {
		var opt_text = n.split("/");
		$("#accessory_list_select").append($("<option></option>")
			.val(n)
			.html(opt_text[opt_text.length - 1])
		);
	});
}
// 获取附件数据
function getAccessory() { return $("#accessory_list").val(); }
// 初始化页面
function initPage()
{
	if ($("#tpl_type").val() == 1) { initPage_form(); }
	else if ($("#tpl_type").val() == 2) { initPage_edit(); }
}
// 初始化使用表单页面
function initPage_form()
{
	var tpl_id = $("#tpl_id").val();
	var editor = $("#editor");
	var tpl_name_areas = $("#tpl_name_areas");
	var url = "new_app.php";
	var pars = { page_status: 1, tpl_id: tpl_id };
	$.post(url, pars, function(xml) {
		var template			= $("template", xml).text().unescapeString();
		var parameters	= JSON.parse($("parameters", xml).text().unescapeString());
		var a			= [];
		__docTpl__		= template;
		$.each(parameters, function(i, n) {
			template = template.replace("#{" + n["name"] + "}", "<span id=\"_tpl_span_" + n["name"] + "\"></span>");
			a[a.length] = n["type"] + ":" + n["name"];
		});
		tpl_name_areas.val(a.join(","));
		editor.html(template);
		$.each(parameters, function(i, n) {
			$("#_tpl_span_" + n["name"]).html(getTplInput2(n["name"], n["type"], n["css"], { content: n["content"], options: n["options"] }));
		});
	})
}
// 初始化使用编辑器填写页面
function initPage_edit()
{
	var tpl_id = $("#tpl_id").val();
	var url = "new_app.php";
	var pars = { page_status: 4, tpl_id: tpl_id };
	$.post(url, pars, function(xml) {
		var tpl_content = $("template", xml).text().unescapeString();
		$("#fcked").val(tpl_content);
		show_FCKEditor("fcked", { width: 580, height: 400 });
	});
}
// 初始化“收件人：”按钮
function initShowDocReceiver()
{
    //if ($("#is_master").val() == 1)  // 如果是主管的话
    //{
		$("#show_doc_receiver").click(function() {
			$("#doc_receive").modal({
				onShow: function() { m(1); },
				onClose: function() { m(0); }
			});
		});
    //}
}
// 初始化“选择收件人”的表单选择
function initDocReceiverSelection()
{
	getCompanyListViaJsShort("#company_list", -1);
	$("#company_list").click(function() {
		getUserListViaJsShort("#doc_receiver", $(this).val(), -1, $("#user_id").val());
	});
}
/* 点击“选择接收人”的“确定” */
function initDocReceiverOK()
{
	$("#doc_receiver_ok").click(function() {
		if ($.trim($("#doc_receiver").html()) == "" || $("#doc_receiver").val() == -1)
		{
			alert("请选择收件者！");
			return false;
		}
		else
		{
			var str = $("#company_list option:selected").html() + " -> "
					// + $("#section_list option:selected").html() + " -> "
					+ $("#doc_receiver option:selected").html();
			$("#doc_to_zh").val(str);
			$("#doc_to").val($("#doc_receiver").val());
			m(0);
		}
	});
}
// 初始化发送
function initApplyGo()
{
	$("#apply_go").click(function() {
		if (!formValidate()) { return false; }
		var url = "new_app.php";
		var pars = {
			page_status: 2,
			tpl_id: $("#tpl_id").val(),
			from_id: $("#user_id").val(),
			to_id: $("#doc_to").val(),
			title: $("#doc_title").val(),
			instancy: $("#instancy").val(),
			accessory: $("#accessory_list").val()
		};
		// 表单填写方式
		if ($("#tpl_type").val() == 1)
		{
			var content = __docTpl__;
			var h = {};
			var inputs = $("#tpl_name_areas").val().split(",");
			$.each(inputs, function(i, n) {
				var key = n.split(":")[0];
				var value = n.split(":")[1];
				if (key == "t" || key == "l" || key == "a" || key == "p" || key == "s")
				{
					h[value] = $("#_formfill_" + value).val();
				}
				else if (key == "r")
				{
					h[value] = $("input:radio[@name='_formfill_" + value + "']:checked").val();
				}
				else if (key == "c")
				{
					var t = [];
					$("input:checkbox[@name='_formfill_" + value + "']:checked").each(function() { t[t.length] = $(this).val(); });
					h[value] = t.join(",");
				}
			});
			$.each(h, function(i, n) {
				content = content.replace("#{" + i + "}", n);
			});
			pars["content"] = content;
		}
		// 编辑器填写方式
		else if ($("#tpl_type").val() == 2)
		{
			pars["content"] = get_FCKData("fcked");
		}
		$.post(url, pars, function(text) {
			if (/Success/.test(text)) { alert(text); window.close(); }
			else { alert(text); }
		});
		return false;
	});
} 
// 数据检验
function formValidate()
{
	if ($.trim($("#doc_title").val()) == "") { alert("请输入申请主题！"); $("#doc_title").focus(); return false; }
	if ($("#doc_to").val() == -1) { alert("请点击“收件者”按钮选择收件人！"); return false; }
	if ($("#tpl_type").val() == 2 && $.trim(get_FCKData("fcked")) == "") { alert("请填写内容！"); return false; }
	return true;
}
// 控制 modal 的隐现
function m(f) { modalShowClose("#opration_bar input, #table_level1 input, #table_level1 select", f); }
